//
//  SetOilMoneyViewController.m
//  carcareIOS
//
//  Created by wr on 16/4/11.
//  Copyright © 2016年 chezheng. All rights reserved.
//

#import "SetOilPriceViewController.h"

#import "OilCityViewController.h"

#import "NetCity.h"
#import "CityModel.h"
#import "FuelMgr.h"
#import "FuelPriceModel.h"

#define CELL_HEIGHT (50)
#define CELL_HEIGHT_BTN (115)
#define SECTION_HEIGHT (11)

typedef NS_ENUM(NSInteger , View_Type) {
    View_Type_Place = 10,//所在地cell 的 右侧label
    View_Type_LeftL = 100,//油价设置左侧label
    View_Type_CenterL = 150,//油价设置的中心Label
    View_Type_RightImageV = 200,//油价设置右侧的imageview
    View_Type_PriceView = 250,//价格cell的背景view
    View_Type_Btn = 300,//cell上面的覆盖按钮
};
@interface SetOilPriceViewController ()

@property (nonatomic , readonly) NSArray * titleArray;

@property (nonatomic , assign) CGFloat priceCellHeight;

//@property (nonatomic , assign) NSInteger priceCellCount;

@property (nonatomic , copy) NSArray * priceDataArr;

@end

@implementation SetOilPriceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createTableView];
    self.title = @"设置油价";
    __weak __typeof(self) wself = self;
    [self navSetupLeftTitle:@"取消" action:^{
        [[FuelMgr sharedInstance]cancelResetDefault];
        [wself dismissViewControllerAnimated:YES completion:nil];
    }];
    
}
- (void)createTableView
{
    self.tableView.frame = CGRectMake(0, 0 , __MAIN_WIDTH , __MAIN_HEIGHT_64 );
    self.tableView.backgroundColor = [Theme backGroundColor];
    self.tableView.separatorColor = [Theme lineNewColor];
    self.tableView.bounces = (__MAIN_HEIGHT == 480 ? YES : NO);

    self.priceCellHeight = CELL_HEIGHT;
    
}
- (NSArray *)titleArray
{
    return @[@[@"所在地"],@[@"空白"],@[@"油价"],@[@"保存"]];
}
#pragma mark - tableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.titleArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return (section != 2 ? [self.titleArray[section] count] : 1);
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 2){
        self.priceCellHeight = CELL_HEIGHT * self.priceDataArr.count;
        if (self.priceDataArr.count == 0) {
            return CELL_HEIGHT;
        }
    }
    
    return (indexPath.section == 1 ? SECTION_HEIGHT : (indexPath.section == 3 ? CELL_HEIGHT_BTN : (indexPath.section == 0 ? CELL_HEIGHT : self.priceCellHeight)));
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell;
    CGFloat labelX = 20.5 * __MAIN_RATIO_375;
    switch (indexPath.section) {
            //所在地
        case 0:
        {
            NSString * cellID = @"photoCellID";
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
                UILabel * leftLabel = [Factory labelWithFrame:CGRectMake(labelX, 0, 60, CELL_HEIGHT) font:FONT_DEFAULT_Light(16) text:self.titleArray[indexPath.section][indexPath.row] textColor:[Theme wordGrayColor] onView:cell textAlignment:NSTextAlignmentLeft];
                UIImage * rightImage = ImageNamed(@"cell_right");
                [Factory imageViewWithCenter: CGPointMake(__MAIN_WIDTH - 25, CELL_HEIGHT / 2) image:rightImage onView:cell];
                UILabel * placeLabel = [Factory labelWithFrame:CGRectMake(leftLabel.right, 0, __MAIN_WIDTH - 25 - rightImage.size.width - leftLabel.right, CELL_HEIGHT) font:FONT_DEFAULT_Light(14) text:@"" textColor:[Theme wordColor] onView:cell textAlignment:NSTextAlignmentRight];
                placeLabel.numberOfLines = 1;
                placeLabel.tag = View_Type_Place;
            }
            UILabel * placeLabel = (UILabel *)[cell viewWithTag:View_Type_Place];
            placeLabel.text = [FuelMgr sharedInstance].showChoiceCity;
            
        }
            break;
            
            //油价
        case 2:
        {
            NSString * cellID = @"oilMoneyCellID";
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
                
                [Factory labelWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, CELL_HEIGHT) font:FONT_DEFAULT_Light(14) text:@"暂时获取不到油价数据，请重新选择" textColor:[Theme wordGrayColor] onView:cell textAlignment:NSTextAlignmentCenter];

                UIView * backCellView = [[[UIView viewWithFrame:CGRectMake(14 * __MAIN_RATIO_375, 0, __MAIN_WIDTH - 14 * __MAIN_RATIO_375 * 2, self.priceCellHeight )] resetBackgroundColor:[UIColor whiteColor]] setupOnView:cell];
                backCellView.layer.borderColor = [Theme lineColor].CGColor;
                backCellView.layer.borderWidth = 0.5;
                backCellView.layer.masksToBounds = YES;
                backCellView.layer.cornerRadius = 2;
                backCellView.tag = View_Type_PriceView;
                cell.backgroundColor = [Theme backGroundColor];
                
            }
            UIView * backCellView = [cell viewWithTag:View_Type_PriceView];
            [backCellView removeAllSubviews];
            [backCellView setHeight:self.priceCellHeight];
            
            for (int index = 0 ; index < self.priceDataArr.count; index ++)
            {
                FuelPriceModel * model = self.priceDataArr[index];
                UIView * smallView = [[[UIView viewWithFrame:CGRectMake(15 * __MAIN_RATIO_375, CELL_HEIGHT * index, backCellView.width - 15 * __MAIN_RATIO_375 * 2, CELL_HEIGHT)] resetBackgroundColor:[UIColor clearColor]] setupOnView:backCellView];
                if(index != self.priceDataArr.count - 1)[[[UIView viewWithFrame:CGRectMake(0 , smallView.height - 0.5, smallView.width, 0.5)] resetBackgroundColor:[Theme lineColor]] setupOnView:smallView];
                
                CGFloat labelX = 8 * __MAIN_RATIO_375;
                UILabel * leftLabel = [Factory labelWithFrame:CGRectMake(labelX, 0, 70, smallView.height) font:FONT_DEFAULT_Light(18) text:@"" textColor:[Theme wordGrayColor] onView:smallView textAlignment:NSTextAlignmentLeft];
                leftLabel.attributedText = [self titleWithNameStr:[model.showFuelLabel componentsSeparatedByString:@"#"][0] withUnitStr:@"#" withUnitFontSize:13];
                leftLabel.numberOfLines = 1;
                leftLabel.tag = View_Type_LeftL + index;
                
                UIImage * choiceImage = ImageNamed(@"choiceOilCellImage");
                UIImageView * choiceImageV = [Factory imageViewWithCenter: CGPointMake(smallView.width - 7 * __MAIN_RATIO_375 - choiceImage.size.width / 2, CELL_HEIGHT / 2) image:choiceImage onView:smallView];
                [choiceImageV setHidden: YES];
                choiceImageV.tag = View_Type_RightImageV + index;
                
                UILabel * centerLabel = [Factory labelWithFrame:CGRectMake(leftLabel.right, 0, smallView.width - leftLabel.right * 2, smallView.height) font:FONT_DEFAULT_Light(18) text:@"" textColor:[Theme wordGrayColor] onView:smallView textAlignment:NSTextAlignmentCenter];
                centerLabel.tag = View_Type_CenterL + index;
                centerLabel.attributedText = [self titleWithNameStr:[NSString stringWithFormat:@"%.02f",model.price] withUnitStr:@"元/升" withUnitFontSize:13];
                
                UIButton * smallButton = [[UIButton buttonEmptyWithFrame:smallView.bounds click:nil] setupOnView:smallView];
                smallButton.tag = View_Type_Btn + index;
                [smallButton addTarget:self action:@selector(cellButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                if (([[FuelMgr sharedInstance].choiceFuelPriceModel.fuelLabel isNotNil] && [[FuelMgr sharedInstance].choiceFuelPriceModel.fuelLabel isEqualToString:model.fuelLabel]) || (index == 0 && ![[FuelMgr sharedInstance].choiceFuelPriceModel.fuelLabel isNotNil])) {
                    [self cellButtonClick:smallButton];
                }
            }
            
            
        }
            break;
        case 3:
        {
            NSString * cellID = @"btnCellID";
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
                cell.backgroundColor = [UIColor clearColor];
                CGFloat buttonH = 45;
                
                __weak __typeof(self) wself = self;
                //保存按钮
                [ViewFactory buttonWithFrame:CGRectMake(14 * __MAIN_RATIO_375, (CELL_HEIGHT_BTN - buttonH) / 2, __MAIN_WIDTH - 14 * __MAIN_RATIO_375 * 2, buttonH)  title:self.titleArray[indexPath.section][indexPath.row] normalColor:[Theme mainColor] highlightColor:[[Theme mainColor] colorWithAlphaComponent:0.7] disabledColor:[Theme wordGrayColor] inView:cell action:^{
                    [wself saveBtnClick];
                    
                }];
                
            }
        }
            break;
            //section view cell
        case 1:

        {
            NSString * cellID = @"noCellID";
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
                cell.backgroundColor = [Theme backGroundColor];
                [[[UIView viewWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, 0.5)] resetBackgroundColor:[Theme lineColor]] setupOnView:cell];
            }
        }
            break;
        default:
            break;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark - 保存按钮
- (void)saveBtnClick
{
    NSString * errMessage;
    if (![[FuelMgr sharedInstance].showChoiceCity isNotNil]) {
        errMessage = @"请选择所在地";
    }else if (![[FuelMgr sharedInstance].choiceFuelPriceModel.fuelLabel isNotNil])
    {
        errMessage = @"请选择油价";
    }
    if ([errMessage isNotNil]) {
        [AlertMgr showShortWarnTextTips:@[errMessage]];
    }else //此处保存按钮事件
    {
        __weak __typeof(self) wself = self;
        [[FuelMgr sharedInstance] resetDefaultSuccess:^{
            [AlertMgr showShortSuccessTextTips:@[@"油价设置成功"]];
            [wself dismissViewControllerAnimated:YES completion:nil];
        } fail:^{
            [AlertMgr showShortNoNetworkTextTips:@[@"网络出错"]];
        }];
    }
}
#pragma mark - 生成使用的attribute str
- (NSMutableAttributedString *)titleWithNameStr:(NSString *)nameStr withUnitStr:(NSString *)unitStr withUnitFontSize:(NSInteger)unitFontSize
{
    NSString * str = [NSString stringWithFormat:@"%@%@",nameStr, unitStr];
    NSMutableAttributedString * attributeStr = [[NSMutableAttributedString alloc]initWithString:str];
    if([unitStr length] > 0)
    {
        NSRange range = NSMakeRange([str length] - [unitStr length], [unitStr length]);
        [attributeStr addAttribute:NSFontAttributeName value:FONT_DEFAULT_Light(unitFontSize) range:range];
    }
    return attributeStr;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
        {
            __weak __typeof(self) wself = self;
            [[NetCity provinces] requestSuccess:^(id JSON) {
                NSArray *tmp = JSON[@"infolist"];
                NSMutableArray *arr = [NSMutableArray arrayWithCapacity:tmp.count];
                for (int i = 0; i < tmp.count; i++) {
                    [arr addObject:[[CityModel alloc] initWithDic:tmp[i]]];
                }
                OilCityViewController *vc = [[[OilCityViewController alloc] initWithTableRefreshType:TYPE_TABLE_REFRESH_NONE] navSetupBackItemWithIdentification:BACK_ICON_TITLE];
                vc.title = @"选择省份";
                [vc fillCitys:arr];
                [wself.navigationController pushViewController:vc animated:YES];
            }];
        }
            break;
            
        default:
            break;
    }
}
#pragma mark - 油价设置按钮后重置页面UI
- (void)reloadPriceCellView:(NSInteger)selectIndex
{

    UIView * backCellView = [self.tableView viewWithTag:View_Type_PriceView];
    for (int index = 0 ; index < self.priceDataArr.count; index ++)
    {
        UILabel * leftL = (UILabel *)[backCellView viewWithTag:View_Type_LeftL + index];
        UILabel * centerL = (UILabel *)[backCellView viewWithTag:View_Type_CenterL + index];
        UIImageView * rightImageV = (UIImageView *)[backCellView viewWithTag:View_Type_RightImageV + index];
        
        if (selectIndex == index) {
            [leftL setTextColor:[Theme mainColor]];
            [centerL setTextColor:[Theme mainColor]];
            [rightImageV setHidden:NO];
        }else
        {
            [leftL setTextColor:[Theme wordGrayColor]];
            [centerL setTextColor:[Theme wordGrayColor]];
            [rightImageV setHidden:YES];
        }
    }
}
//选择油价设置的按钮
- (void)cellButtonClick:(UIButton *)sender
{
    
    FuelPriceModel * model = self.priceDataArr[sender.tag - View_Type_Btn];
    [FuelMgr sharedInstance].choiceFuelPriceModel.fuelLabel = model.fuelLabel;
    [self reloadPriceCellView:sender.tag - View_Type_Btn];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    __weak __typeof(self) wself = self;
    [[FuelMgr sharedInstance]getFuelPriceSuccess:^(NSArray *prices) {
        wself.priceDataArr = prices;
        [wself.tableView reloadData];
    } fail:^{
        
    }];
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
